package com.tianxia120.website.data.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @createTime: 2018/1/4
 * @author: HingLo
 * @description: 定义xss攻击具体实现
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    /**
     * 构造方法
     *
     * @param servletRequest
     */
    XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    /**
     * 过滤参数值
     *
     * @param parameter 参数名称
     * @return 过滤处理后的值
     */
    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }

    /**
     * 过滤参数名称
     *
     * @param parameter
     * @return
     */
    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }

    /**
     * 请求头过滤
     *
     * @param name 请求头的名称
     * @return 过滤的值
     */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }

    /**
     * 真正的过滤规则
     *
     * @param value 值
     * @return 返回过滤后的值
     */
    private String cleanXSS(String value) {
        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
        value = value.replaceAll("'", "&#39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\"\\\'][\\s]*javascript:(.*)[\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        //参数空格过滤
        return value.trim();
    }

}